package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 支持LayUI + Thymeleaf模板 静态分页方式（类似JSP）
     *
     * @param model
     * @return 模板目录下 hellouser.html 进行解析
     */
    @RequestMapping("/tofindAll")
    public String tofindAll(Model model) {
        List<User> userList = userService.findAll();
        model.addAttribute("userlist", userList);
        return "hellouser";
    }

    /**
     * LayUI 动态表格数据 分页返回例子
     * @param page 显示页号
     * @param limit 每页的记录数
     * @return LayUI要求的
     */
    @GetMapping("/tofindAll_json")
    @ResponseBody
    public Map<String, Object> tofindAll_json(@RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "10") Integer limit){
        List<User> userList = userService.findAll();

        int total = userList.size();

        // 计算当前需要显示的数据下标起始值
        int startIndex = (page - 1) * limit;
        int endIndex = Math.min(startIndex + limit,total);

        List<User> pageList = userList.subList(startIndex,endIndex);
        Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap.put("code", 0);  //此处为0
        resultMap.put("msg", ""); //此处为空
        resultMap.put("count", userList.size());//此处放入总的数据数量
        resultMap.put("data", pageList); //此处应该放入实际页的数据

        return resultMap;
    }


}
